package me.ahy231.auth.component;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import java.util.HashSet;

/**
 * @author ahy231
 * @date 2021/6/27 21:06
 * @description
 */
@Component
public class UserRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        HashSet<String> userRoles = new HashSet<>();
        for (Object principal : principals.asList()) {
            if (principal instanceof Long) {
                long openId = (Long) principal;
                if (openId == 0) {
                    userRoles.add(UserRole.ADMIN.toString());
                }
                userRoles.add(UserRole.COMMON.toString());
            }
        }
        return new SimpleAuthorizationInfo(userRoles);
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal = (String) token.getPrincipal();
        Long openId = Long.parseLong(principal);
        return new SimpleAuthenticationInfo(openId, token.getCredentials(), this.getName());
    }
}
